//
//  SHNetworkTools.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/25.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit
import AFNetworking

// 请求方式枚举
enum SHNetworkToolsType: String {
    case GET = "GET"
    case POST = "POST"
}

class SHNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let sharedTools: SHNetworkTools = {
        let tools = SHNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain,text/html")
        
        return tools
    }()
    
    // 网络get和post请求全局方法
    func request(type: SHNetworkToolsType, urlString: String, parameters: AnyObject?, success: (response: AnyObject?)->(), failure: (error: NSError)->()) {
        //get请求
        if type == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }else {
            // post请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
    }

}
//MARK: - 请求OAuth界面数据
extension SHNetworkTools {
    //请求userAccount
    func oauthLoadUserAccount(code: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()) {
        // 请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": K_APPKEY,
            "client_secret": K_APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": K_APPREDIRECT_URI
        ]
        request(.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    // 请求用户信息数据
    func oauthLoadUserInfo(userAccount: SHUserAccount, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid!
        ]
        request(SHNetworkToolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

// MARK: - 请求首页微博数据
extension SHNetworkTools {
    
    func homeLoadData(sinceId: Int64, maxId: Int64, success: (response: AnyObject?)->(), failure: (error: NSError)->()) {
        // 请求urlString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = [
            "access_token": SHUserAccountViewModel.sharedTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        
        request(.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

// MARK: - 发送微博
extension SHNetworkTools {
    // 发送文字微博
    func composeUploadText(status: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token":SHUserAccountViewModel.sharedTools.accessToken!,
            "status":status
        ]
        request(SHNetworkToolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    // 发送图片微博
    func composeUploadPic(status: String, imageList: [UIImage], success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token": SHUserAccountViewModel.sharedTools.accessToken!,
            "status": status
        ]
        // 请求必须用POST方式提交，并且注意采用multipart/form-data编码方式；
        POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            /*
            - 01参数: 客户端需要提交的二进制文件
            - 02参数: 服务器端给客户端提供的名字 服务器才知道你传的是什么模块里面的图片
            - 03参数: 服务器端保存文件的文件夹  客户端 可以随意传
            - 04参数: 代表客户端提交的二进制文件格式 一般可以使用该类型 application/octet-stream 忽略格式
            */
            // 获得二进制数据
            // 发送一张图片
            //            let data = UIImagePNGRepresentation(self.composePictureView.imageList.first!)!
            //            formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            
            // 发送多张图片
            for i in 0..<imageList.count {
                let data = UIImagePNGRepresentation(imageList[i])!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "any", mimeType: "application/octet-stream")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                success(response: response)
            }) { (_, error) -> Void in
                failure(error: error)
        }
    }
    
}









